package com.aote.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import com.aote.util.StringHelper;
import com.browsesoft.baseadapter.AdvancedSimpleEntity;
import com.browsesoft.hibernate.HibernateUtil;
import com.browsesoft.htmlcomponent.HTMLFormComponent;
import com.browsesoft.htmlcomponent.HTMLFormModel;
import com.browsesoft.htmlcomponent.HTMLPage;
import com.browsesoft.oa.BSHttpServletRequest;
import com.browsesoft.util.SessionHelper;

/**
 * 用于客户端的Form表单向服务器端要数据的处理
 */
public class AjaxFormServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Session hibSession = HibernateUtil.getSessionFactory()
				.getCurrentSession();
		hibSession.beginTransaction();
		try {
			response.setContentType("text/html; charset=GBK");
			// 从session中找到页面
			String pageName = request.getParameter("pagename");
			HttpSession session = request.getSession();
			HTMLPage page = SessionHelper.getPage(session, pageName);
			// 让页面处理请求，达到让表单处理请求的目的
			BSHttpServletRequest bsrequest = new BSHttpServletRequest(request);
			page.dispatch(bsrequest, response);
			// 得到页面的onload结果
			page.setOnload();
			String onload = page.getElement().getAttribute("onload");
			String resp = "{\"onload\":\"" + onload + "\",";
			// 从表单中得到结果，返回ajax
			String fcname = HTMLFormComponent.class.getName();
			HTMLFormComponent comp = (HTMLFormComponent) page
					.getComponentsByClassName(fcname).get(0);
			HTMLFormModel model = (HTMLFormModel) comp.getModel();
			Map ht = model.getAttributes();
			if (model instanceof AdvancedSimpleEntity) {
				ht = ((AdvancedSimpleEntity) model).formatDatas(ht);
			}
			String str = StringHelper.mapToJSON(ht);
			// 把onload属性与输入框计算结果合并
			resp += "\"fields\":" + str + "}";
			Writer writer = response.getWriter();
			System.out.println(resp);
			writer.write(resp);
			writer.close();
			if (hibSession.isOpen()) {
				hibSession.getTransaction().commit();
			}
		} catch (Exception e) {
			if (hibSession.isOpen()) {
				hibSession.getTransaction().rollback();
			}
			e.printStackTrace();
		}
	}
}
